/**
 * 版权所有 @鸿名物联 
 * 未经授权，禁止侵权和商业用途，违法必究
 * 联系QQ：2224313811 
 * 
 */
package com.lp.authority;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lp.bo.UserInfoBO;
import com.lp.cache.CacheName;
import com.lp.cache.ProCacheUtil;
import com.lp.cfg.ProConfig;
import com.lp.common.Code;
import com.lp.util.CommonUtil;
import com.lp.util.LogUtil;
import com.lp.util.ObjectUtil;
import com.lp.util.ResultMapUtils;

import net.sf.json.JSONObject;

public class AuthorityIntercept {

	/**
	 * 权限判断
	 * 
	 * @param req
	 * @param response
	 * @return
	 */
	public static Boolean AutjorityIntercept(HttpServletRequest req, HttpServletResponse response) {
		// uri
		String requestUri = req.getRequestURI();
		// url
		String requestUrl = req.getRequestURL().toString();
		// method
		String requestMethod = req.getMethod();
		// key -- GET请求不包含KEY WEB请求的时候，全部包含Session
		String userKey = req.getHeader(ResultMapUtils.USER_KEY);
		try {
			if (requestUrl.contains("/login") || requestUrl.contains("/register") || requestUrl.contains("/password") || 
					requestUrl.contains("/validate/code") || requestUrl.contains("/security_code") || requestUrl.contains("/upload")
					|| requestUrl.contains("/mail") || requestUrl.contains("/bind") || requestUrl.contains("/live") || 
					requestUrl.contains("/mqtt") ||  requestUrl.contains("/baidu") || requestUrl.contains("/vp") ||requestUrl.contains("/noauth") || requestUrl.endsWith("/") ) {
				return true;
			} else {
				if (ObjectUtil.isNotEmpty(userKey) || requestMethod.equals("PUT") || requestMethod.equals("POST")
						|| requestMethod.equals("DELETE")) {
					// userKey 不能为空
					if (ObjectUtil.isNotEmpty(ProCacheUtil.getCache(CacheName.USERINFO, userKey,new Object()) )) {
						return true ;
					} else {
						JSONObject resultData = new JSONObject();
						resultData.put("status", Code.ResponseCode.SystemCode.NO_AUTHORIZATION);
						resultData.put("statusMsg", "NO ACCESS");
						PrintWriter out = response.getWriter();
						out.write(resultData.toString());
						out.flush();
						return false ;
					}
				} else {
					UserInfoBO user = (UserInfoBO) req.getSession().getAttribute("user");
					if (ObjectUtil.isNotEmpty(user)) {
						return true;
					} else {
						try {
							if(CommonUtil.checkReqUtil.checkAgentIsMobile(req)){
								response.sendRedirect( ProConfig.LOCAL_DOMAIN + "/service/wiot/login" );	
							}else{
								response.sendRedirect( ProConfig.LOCAL_DOMAIN + "/service/iot/login" );								
							}
						} catch (IOException e) {
							e.printStackTrace();
						}
						return false;
					}
				}
			}
		} catch (Exception e) {
			LogUtil.errorLog(e);
			return false;
		}
	}

}
